package com.example.demo.service;

import com.example.demo.model.request.ApiRequest;
import com.example.demo.model.request.FrontendRequest;
import com.example.demo.model.response.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.HttpHeaders;

@Service
public class PredictionService {
    // 外部API地址（与示例中一致）
    private static final String API_URL = "http://47.109.56.105:8000/predict";

    private final RestTemplate restTemplate;

    // 构造注入RestTemplate
    public PredictionService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 处理预测流程
     * @param frontendRequest 前端输入参数
     * @return 外部API返回的结果
     */
    public ApiResponse predict(FrontendRequest frontendRequest) {
        // 1. 转换前端请求为外部API需要的格式
        ApiRequest apiRequest = convertToApiRequest(frontendRequest);

        // 2. 发送POST请求到外部API
        ResponseEntity<ApiResponse> responseEntity;
        try {
            responseEntity = restTemplate.postForEntity(
                    API_URL,
                    apiRequest,  // 自动序列化为JSON
                    ApiResponse.class  // 响应自动反序列化为ApiResponse
            );
        } catch (Exception e) {
            // 处理调用异常（如网络错误、超时等）
            throw new RuntimeException("调用外部API失败：" + e.getMessage());
        }

        HttpStatusCode status = responseEntity.getStatusCode();
        if (status.is2xxSuccessful()) {
            return responseEntity.getBody();

        }
        if (status.is3xxRedirection()) {
            String location = responseEntity.getHeaders().getFirst(HttpHeaders.LOCATION);
            if (location == null || location.isBlank()) {
                throw new RuntimeException("外部API返回重定向但缺少Location头：" + status);
            }
            try {
                ResponseEntity<ApiResponse> redirected = restTemplate.postForEntity(
                        location,
                        apiRequest,
                        ApiResponse.class
                );
                if (redirected.getStatusCode().is2xxSuccessful()) {
                    return redirected.getBody();
                }
                throw new RuntimeException("外部API重定向后返回非成功状态：" + redirected.getStatusCode());
            } catch (Exception e) {
                throw new RuntimeException("调用外部API失败：" + e.getMessage());
            }
        }

        throw new RuntimeException("外部API返回非成功状态：" + status);
    }

    /**
     * 转换前端请求到API请求格式
     */
    private ApiRequest convertToApiRequest(FrontendRequest frontendRequest) {
        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setGpa(frontendRequest.getGpa());
        apiRequest.setCet4(frontendRequest.getCet4());
        apiRequest.setMath1(frontendRequest.getMath1());
        apiRequest.setMath2(frontendRequest.getMath2());
        apiRequest.setEnglish1(frontendRequest.getEnglish1());
        apiRequest.setEnglish2(frontendRequest.getEnglish2());
        apiRequest.setEnglish3(frontendRequest.getEnglish3());
        apiRequest.setEnglish4(frontendRequest.getEnglish4());
        return apiRequest;
    }
}